/**
 * DSM - Distributed Search Manager
 * Developed by Milspec Research International Pty Ltd
 * $Author: skahl $
 * $Revision: 1.7 $
 * $Date: 2007/02/07 23:08:09 $
 * (c)Copyright 2004
 * education.au limited
 * DEST
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the names education.au limited, DEST nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 * To the extent permitted by law, the copyright owners of this software and
 * its contributors:
 * (i) exclude all warranties in relation to the software; and
 * (ii) exclude liability for all losses, costs, expenses and damages arising
 * in any way from the use of the software whether arising from or in
 * relation to breach of contract, negligence or any other tort, in equity
 * or otherwise. If the software is in breach of a warranty which is
 * implied by law, the copyright owners and contributors liability is
 * limited to the replacement of the software.
 *
 * @author	gsingh
 */

package au.edu.educationau.opensource.dsm.adapters;

import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;

import au.edu.educationau.opensource.dsm.adapters.contenthandler.EDNAContentHandler;
import au.edu.educationau.opensource.dsm.DeusExMachina;
import au.edu.educationau.opensource.dsm.adapters.SearchAdapter;
import au.edu.educationau.opensource.dsm.cache.DiskCacheEntry;
import au.edu.educationau.opensource.dsm.obj.SearchCriteria;
import au.edu.educationau.opensource.dsm.worker.ResultSetUnifier;

/**
 * Generic Edna XML format adapter. Can be used to facade other searches
 */

public class EDNASearchAdapterImpl extends SearchAdapter {
	private int startValue = 1;

	/** Parent constructor */
	public EDNASearchAdapterImpl() {
		super();
	}

	/**
	 * See the SearchAdapter abstract method doPrime
	 * 
	 * @exception Throwable
	 */
	public void doPrime() throws Throwable {
		SearchCriteria criteria = super.getSearchCriteria();
		addToURLBuffer("querytext=");
		addToURLBuffer(URLEncoder.encode(criteria.getQuery(), "UTF-8"));
		addToURLBuffer("&casesensitive=");
		addToURLBuffer(criteria.isCaseSensitive() ? "yes" : "no");
		addToURLBuffer("&count=");
		addToURLBuffer(super.getProperties().getBatchSize());
		addToURLBuffer("&word=");
		addToURLBuffer(criteria.getKeywordConstraint());
		addToURLBuffer("&start=");
		addToURLBuffer(startValue);

		if (criteria.hasCustomParams()) {
			String param;
			String[] values;
			String adapterName = super.getProperties().getAdapterCode() + ".";
			for (Enumeration params = criteria.getCustomParams(); params.hasMoreElements();) {
				param = (String) params.nextElement();
				if (param.startsWith(adapterName) && param.length() > adapterName.length()) {
					values = criteria.getCustomParamValues(param);
					for (int i = 0; i < values.length; i++) {
						String value = values[i];
						if (value != null) {
							value = URLEncoder.encode(value, "UTF-8");
						}
						addToURLBuffer("&");
						addToURLBuffer(param.substring(adapterName.length()));
						addToURLBuffer("=");
						addToURLBuffer(value);
					}
				}
			}
		}
	}

	/**
	 * See the SearchAdapter abstract method doPerform
	 * 
	 * @exception Throwable
	 */
	public ArrayList doPerform() throws Throwable {
		EDNAContentHandler eCHandler = new EDNAContentHandler();
		eCHandler.setSearchAdapterProperties(super.getProperties());
		DiskCacheEntry entry = DeusExMachina._DiskCache().getEntry(super.getAugmentedSearchURL());
		if (null != entry) {
			// Get the responseCode
			if (entry.getResponseCode() != HttpURLConnection.HTTP_OK) {
				super.setResponseCode(entry.getResponseCode());
			}

			Reader reader = entry.getReader();
			if (null != reader) {
				eCHandler = (EDNAContentHandler) ResultSetUnifier.processXML(reader, eCHandler);
			}
		}
		ArrayList batch = eCHandler.getResults();
		super.setTheoreticalAvailableResults(eCHandler.getFound());

		return batch;
	}

	/**
	 * See the SearchAdapter abstract method doNextBatch
	 * 
	 * @exception Throwable
	 */
	public boolean doNextBatch() throws Throwable {
		if (super.getTheoreticalAvailableResults() > super.getProperties().getBatchSize() && super.getProperties().getBatchSize() < super.getSearchCriteria().getMaxResults() && super.getTotalFound() < super.getSearchCriteria().getMaxResults()) {
			startValue = startValue + super.getProperties().getBatchSize();
			return startValue <= 200;
		} else {
			return false;
		}
	}

	/**
	 * See the SearchAdapter abstract method doStopNice
	 * 
	 * @exception Throwable
	 */
	public void doStopNice() throws Throwable {
		// does nothing here
	}

	/**
	 * See the SearchAdapter abstract method doStopForce
	 * 
	 * @exception Throwable
	 */
	public void doStopForce() throws Throwable {
		// does nothing here
	}

	/** Class display string */
	public String toString() {
		return "o.m.d.a.EDNASearchAdapterImpl";
	}
} // -- EOF
